package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.*;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class RemoveCartItemServlet extends HttpServlet {
    private CatalogService catalogService;
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";
    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        Cart cart = (Cart)session.getAttribute("cart");
        AccountService accountService = new AccountService();
        String workingItemId = req.getParameter("workingItemId");

        //将数据库中购物车商品数量置位0
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            try {
                int quantity = 0;
                cart.setQuantityByItemId(workingItemId, quantity);
                accountService.ReserveCart(loginAccount,cart);
            } catch (Exception e) {}
        }

        Item item = cart.removeItemById(workingItemId);
        if (item == null) {
            session.setAttribute("errorMSG","Attempted to remove null CartItem from Cart.");
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
        } else {
            req.getRequestDispatcher(CART_FORM).forward(req,resp);
        }
    }
}
